//
//  KFDEncryptor.m
//  KFD
//
//  Created by JIRENTIANXIANG on 6/5/15.
//  Copyright (c) 2015 KFD. All rights reserved.
//

#import "KFDEncryptor.h"
#import "KFDStringConcatenator.h"
#import "NSString+encryption.h"

#define md5_key @"f6f712249f4b725fac309504d633f839"
#define aes_key @"a6ce962f31d4a3d9"

@implementation KFDEncryptor

+(NSString*)encryptPassword:(NSString *)password
{
    return [password AES128EncryptedStringWithKey:aes_key];
}

+(NSString*)signedParameterListForParameters:(NSDictionary *)parameters withSignature:(NSString *)signature
{
    NSMutableArray* arr=[NSMutableArray array];
    NSArray* keys=parameters.allKeys;
    for (NSString* key in keys) {
        [arr addObject:[NSString stringWithFormat:@"%@=%@",key,parameters[key]]];
    }
    KFDStringConcatenator* concatenator=[KFDStringConcatenator concatenatorWithSeparator:@"&"];
    NSString* parameterList=[concatenator concatenateStringsInArray:arr];
    parameterList=[parameterList stringByAppendingFormat:@"&sign=%@",signature];
    return parameterList;
}

+(NSString*)autoSignedParameterListForParameters:(NSDictionary*)parameters
{
//    NSMutableArray* arr=[NSMutableArray array];
//    NSArray* keys=parameters.allKeys;
//    for (NSString* key in keys) {
//        [arr addObject:[NSString stringWithFormat:@"%@=%@",key,parameters[key]]];
//    }
//    KFDStringConcatenator* concatenator=[KFDStringConcatenator concatenatorWithSeparator:@"&"];
//    NSString* parameterList=[concatenator concatenateStringsInArray:arr];
//    parameterList=[parameterList stringByAppendingFormat:@"&sign=%@",[KFDEncryptor signatureGeneratedFromParameters:parameters]];
//    return parameterList;
    return [KFDEncryptor signedParameterListForParameters:parameters withSignature:[KFDEncryptor signatureGeneratedFromParameters:parameters]];
}

+(NSString*)signatureGeneratedFromParameters:(NSDictionary *)parameters
{
    return [KFDEncryptor signatureGeneratedFromParameters:parameters keyValueSeparator:@"=" parameterSeparator:@"&"];
}

+(NSString*)signatureGeneratedFromParameters:(NSDictionary *)parameters keyValueSeparator:(NSString *)kvSeparator parameterSeparator:(NSString *)pSeparator
{
    NSArray* keys=parameters.allKeys;
    NSMutableArray* arr=[NSMutableArray array];
    KFDStringConcatenator* concatenator=[KFDStringConcatenator concatenatorWithSeparator:pSeparator];
    for (NSString* key in keys) {
        NSString* parameter=[NSString stringWithFormat:@"%@%@%@",key,kvSeparator,parameters[key]];
        [arr addObject:parameter];
    }
    NSArray* sortedArr=[arr sortedArrayUsingSelector:@selector(compare:)];
    NSString* str=[[concatenator concatenateStringsInArray:sortedArr] stringByAppendingFormat:@"%@key%@%@",pSeparator,kvSeparator,md5_key];
    return str.md5;
}

@end
